#include "stdafx.h"
#include "Network.h"
#include "NetMsg.h"
#include "Socket.h"

namespace cupid
{
DECLARE_SINGLETON_MEMBER(Network);

Network::Network(void)
{
	m_ready		= false;
	m_socket		= NULL;
}

Network::~Network(void)
{
	destroy();
}
BOOL Network::init( const char* szServerIP, int serverPort )
{
	if(!szServerIP || serverPort<0)
		return false;

	if (m_socket)
		return true;

	this->destroy();

	// init now
	m_bytesReceived	= 0;
	m_bytesSend		= 0;

	//if(::ClientSocketInit(pszServerIP, nServerPort))
	m_socket = new Socket;
	if (!m_socket)
		return false;

	if(m_socket->create((char*)szServerIP, serverPort))
	{
		this->m_ready	=true;
		return true;
	}
	else
	{
		this->m_ready	=false;
		return false;
	}
	return true;
}

void Network::processNetMsg()
{
	if (m_socket == NULL)
		return;
	try {

		if (!m_socket->check())		// network failed
		{
			this->destroy();
			return;
		}

		while (true)
		{
			char buffer[1024];
			int nSize	=sizeof(buffer);
			char* pbufMsg	=buffer;

			if (!m_socket->receiveMsg(pbufMsg, nSize))
				break;

			while (true)
			{
				DWORD	dwCurMsgSize	=NetMsg::getSize(pbufMsg, nSize);
				if((int)dwCurMsgSize > nSize || dwCurMsgSize <=0)	// broken msg
					break;

				NetMsg* msg	=NetMsg::createMsg(pbufMsg, dwCurMsgSize);
				if(msg)
				{
					int nMsgType	=msg->getType();

					try {

						msg->process(NULL);   

					}
					catch(...)
					{

						char szDumpMsg[4096] = "";
						BYTE* pBuf = (BYTE*)msg->getBuf();
						pBuf += 4;

						int nSize = __min(msg->getSize()-4, 256);
						for (int i=0; i<nSize; i++)
						{
							char szValue[256] = "";
							_itoa_s(pBuf[i], szValue, 16);

							strcat_s(szValue, " ");
							strcat_s(szDumpMsg, szValue);
						}

					}
					delete(msg);

					m_bytesReceived += dwCurMsgSize;
				}

				pbufMsg	+=dwCurMsgSize;
				nSize	-=dwCurMsgSize;
				if(nSize <= 0)
					break;
			}
		}

		m_socket->flush();
	}
	catch(...)
	{
	}
	return;
}


void Network::destroy()
{
	if(m_ready)
	{
		m_socket->flush();
		m_socket->destroy();
		m_ready	=false;
	}

	SAFE_DELETE(m_socket);
}

//////////////////////////////////////////////////////////////////////
BOOL Network::sendMsg( char* bufMsg, DWORD dwSize )
{
	if(!m_ready)
		return false;


	BOOL sucSend;
	try 
	{
		sucSend	=m_socket->sendMsg(bufMsg, dwSize);
	}
	catch(...)
	{	
	}

	m_bytesSend += dwSize;
	return sucSend;
}


}